package cn.tedu._04weibo.controller;
import cn.tedu._04weibo.base.response.jsonresulte;
import cn.tedu._04weibo.base.response.statuscode;
import cn.tedu._04weibo.mapper.mapper;
import cn.tedu._04weibo.pojo.dto.leg;
import cn.tedu._04weibo.pojo.dto.login;
import cn.tedu._04weibo.pojo.entity.user;
import cn.tedu._04weibo.pojo.vo.logvo;
import cn.tedu._04weibo.pojo.vo.uservo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Slf4j
@Tag(name="用户管理")
@RestController
@RequestMapping("/user")
public class ucon
{
    @Autowired
    private mapper mapper;

    @PostMapping("/add")
    @Operation(summary = "用户注册")
    @ApiOperationSupport(order = 10)
    public jsonresulte leg(@RequestBody leg leg)
    {
        log.debug("开始处理用户注册功能");
        String username = leg.getUsername();
        int bb = mapper.selectleg(username);
        if(bb>0)
        {
            return new jsonresulte(statuscode.USERNAME_EXISTS);
        }

        user user = new user();
        BeanUtils.copyProperties(leg,user);
        user.setCreateTime(new Date());
        log.debug("用户注册"+ user);
        mapper.insert(user);
        return jsonresulte.success();
    }

    @PostMapping("/login")
    @Operation(summary = "登录功能")
    @ApiOperationSupport(order = 20)
    public jsonresulte login(@RequestBody login login, HttpSession session)
    {
        log.debug("登录"+ login);
        logvo vo=mapper.selectlogin(login);
        if (vo==null){return new jsonresulte(statuscode.USERNAME_PASSWORD_ERROR);}
        session.setAttribute("user",vo);
        return jsonresulte.success(vo);
    }

    @GetMapping("/current")
    @Operation(summary = "获取当前用户")
    @ApiOperationSupport(order = 30)
    public jsonresulte current(HttpSession session)
    {
        log.debug("获取当前用户");
        uservo vo=(uservo) session.getAttribute("user");
        if (vo==null)
        {return new jsonresulte(statuscode.NOT_LOGIN);}
        return jsonresulte.success(vo);
    }

    @GetMapping("/legout")
    @Operation(summary = "退出登录")
    @ApiOperationSupport(order =40)
    public void logout(HttpSession session)
    {
        log.debug("退出登录");
        session.removeAttribute("user");
    }
}
